package com.jl.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jl.commons.base.BaseController;
import com.jl.commons.constant.Constants;
import com.jl.commons.constant.ErrorCode;
import com.jl.commons.constant.ErrorMessage;
import com.jl.commons.result.DeviceRunStatus;
import com.jl.commons.result.PageDataInfo;
import com.jl.commons.result.ResultData;
import com.jl.commons.utils.BASE64;
import com.jl.model.Device;
import com.jl.service.IDeviceService;
import com.jl.service.IFaultInfoService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 设备表 前端控制器
 * </p>
 *
 * @author JiangJian
 * @since 2019-03-06
 */
@Controller
@RequestMapping("/device")
public class DeviceController extends BaseController {

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private IFaultInfoService faultInfoService;

    @GetMapping("/deviceDataGrid")
    @RequiresPermissions("/device/deviceDataGrid")
    public String deviceList(){
     return "device_list";
    }


    @GetMapping("/add")
    @RequiresPermissions("/device/add")
    public String addDevicePage(ModelMap mp,Long id){
        mp.put("id",id);
        return "device_add";
    }

    @PostMapping("/add")
    @RequiresPermissions("/device/add")
    @ResponseBody
    public ResultData addDevice(String json){
        String value = BASE64.decode(json);
        if(null == value){
            return fail(ErrorCode.BASE64_DECODER_ERROR, ErrorMessage.BASE64_DECODER_ERROR);
        }
        Device device = JSON.parseObject(value,Device.class);
        //判断设备编号是否重复，不能拥有重复编号
        if(deviceService.isDeviceNumberUsed(device.getNumber())){
            //被占用
            return fail(ErrorCode.DEVICE_NUMBER_USED,ErrorMessage.DEVICE_NUMBER_USED);
        }
        deviceService.saveDeviceWithModel(getShiroUser(),device);
        return success(device);
    }

    @RequestMapping(value = "/edit",method = RequestMethod.GET)
    @RequiresPermissions("/device/edit")
    public String editDevicePage(ModelMap mp,Long id){
        mp.put("id",id);
        return "device_add";
    }

    @PostMapping("/edit")
    @RequiresPermissions("/device/edit")
    @ResponseBody
    public ResultData editDevice(String json){
        String value = BASE64.decode(json);
        if(null == value){
            return fail(ErrorCode.BASE64_DECODER_ERROR, ErrorMessage.BASE64_DECODER_ERROR);
        }
        Device device = JSON.parseObject(value,Device.class);
        //判断编号是不是自己的，如果是自己的则表示可以修改
        boolean canUse = deviceService.isDeviceNumberCanUse(device.getNumber(),device.getId());
        if(!canUse){
            return fail(ErrorCode.DEVICE_NUMBER_USED,ErrorMessage.DEVICE_NUMBER_USED);
        }

        deviceService.updateDeviceWithModel(getShiroUser(),device);
        return success(device);
    }


    @PostMapping("/delete")
    @RequiresPermissions("/device/delete")
    @ResponseBody
    public ResultData deletesDevice(String json){
        String value = BASE64.decode(json);
        if(null == value){
            return fail(ErrorCode.BASE64_DECODER_ERROR, ErrorMessage.BASE64_DECODER_ERROR);
        }
        List<Long> ids = JSONArray.parseArray(value,Long.class);
        boolean b = deviceService.deleteDeviceByIds(ids);
        if(b){
            return success();
        }
        return fail();
    }

    @PostMapping("/dataGrid")
    @RequiresPermissions("/device/dataGrid")
    @ResponseBody
    public ResultData deviceDataGrid(Long current,Long pageSize,String searchCol,String searchValue,String json){
        if(current == null || pageSize == null){
            return fail(ErrorCode.PAGE_PARAM_ERROR, ErrorMessage.PAGE_PARAM_ERROR);
        }
        QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(json)){
//            查询
            String value = BASE64.decode(json);
            JSONObject jsonObject = JSONObject.parseObject(value);
            if(null!=jsonObject.getLong("modelId") && jsonObject.getLong("modelId")!=0){
                queryWrapper.eq("t.model_id",jsonObject.getLong("modelId"));
            }
            if(null!=jsonObject.getLong("productionLine") && jsonObject.getLong("productionLine")!=0){
                queryWrapper.eq("t.production_line",jsonObject.getLong("productionLine"));
            }
            if(StringUtils.isNotBlank(jsonObject.getString("number"))){
                queryWrapper.like("t.number",jsonObject.getString("number"));
            }
            if(StringUtils.isNotBlank(jsonObject.getString("name"))){
                queryWrapper.like("t.name",jsonObject.getString("name"));
            }
            if(StringUtils.isNotBlank(jsonObject.getString("modelNumber"))){
                queryWrapper.like("t.model_number",jsonObject.getString("modelNumber"));
            }
            if(StringUtils.isNotBlank(jsonObject.getString("producer"))){
                queryWrapper.like("t.producer",jsonObject.getString("producer"));
            }
            if(StringUtils.isNotBlank(jsonObject.getString("installDate"))){
                queryWrapper.like("t.install_date",jsonObject.getString("installDate"));
            }
        }else{
            if(StringUtils.isNotBlank(searchValue) && StringUtils.isNotBlank(searchCol)){
                if(searchCol.equals(Constants.ID)){
                    queryWrapper.eq("t.id",searchValue);
                }else{
                    queryWrapper.like("t."+searchCol,searchValue);
                }
            }
        }
        PageDataInfo<Map<String,Object>> pageDataInfo =new PageDataInfo<>();
        pageDataInfo.setCurrent(current);
        pageDataInfo.setSize(pageSize);
        deviceService.selectDeviceDataGrid(pageDataInfo,queryWrapper);
        return success(pageDataInfo);
    }



    @GetMapping("/deviceFault")
    @RequiresPermissions("/device/deviceFault")
    public String deviceFaultPage(ModelMap mp,Long id){
        mp.put("id",id);
        return "deviceFaultInfo_list";
    }

    @PostMapping("/deviceFault")
    @RequiresPermissions("/device/deviceFault")
    @ResponseBody
    public ResultData deviceFault(Long current,Long pageSize,Long keyWord,Long deviceId){
        if(current == null || pageSize == null){
            return fail(ErrorCode.PAGE_PARAM_ERROR, ErrorMessage.PAGE_PARAM_ERROR);
        }
        PageDataInfo<Map<String,Object>> pageDataInfo =new PageDataInfo<>();
        pageDataInfo.setCurrent(current);
        pageDataInfo.setSize(pageSize);
        //查询本台设备的故障信息列表(可根据关键词查询)
        faultInfoService.selectDeviceFaultWithKeyWord(pageDataInfo,keyWord,deviceId);
        return success(pageDataInfo);
    }

    @PostMapping("/deviceRunStatus")
    @RequiresPermissions("/device/deviceFault")
    @ResponseBody
    public ResultData deviceFault(Long deviceId,Integer type,String time ){
        DeviceRunStatus deviceRunStatus= deviceService.getDeviceStatus(deviceId,type,time);
        return success(deviceRunStatus);
    }


}
